package cn.smile.utils;

import cn.smile.commons.constant.NumberConstant;
import cn.smile.commons.exceptions.BusinessException;
import cn.smile.commons.response.MyResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

@Slf4j
public class FileUtil {

    /**
     * File 转 MultipartFile
     *
     * @param file 待转换的文件
     * @return 转换后的 MultipartFile
     */
    public static MultipartFile fileToMultipartFile(File file) {
        MultipartFile multipartFile = null;
        try {
            FileInputStream inputStream;
            inputStream = new FileInputStream(file);
            multipartFile = new MyMultipartFile(
                    "file",
                    file.getName(),
                    MediaType.MULTIPART_FORM_DATA_VALUE,
                    inputStream);

        } catch (Exception e) {
            log.error("File 转 MultipartFile 异常, e:", e);
        }
        return multipartFile;
    }

    /**
     * 拆分文件访问URL, 返回文件名称
     *
     * @param url 文件访问路径
     * @return 文件名称
     */
    public static String urlToFileName(String url) {
        String fileName = null;
        if (!ObjectUtils.isEmpty(url)) {
            String[] split = url.split("/");
            fileName = split[split.length - 1];
        }
        return fileName;
    }

    /**
     * 下载网络文件到本地
     *
     * @param fileUrl 网络文件地址
     * @return 本地文件对象
     */
    public static File getFileToLocal(String fileUrl) {
        File localFile;
        try {
            String[] urlSplit = fileUrl.split("\\.");
            String fileName = String.format("%s.%s", UUID.randomUUID(), urlSplit[urlSplit.length - NumberConstant.ONE]);
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(fileUrl).openConnection();
            httpUrl.connect();
            InputStream in = httpUrl.getInputStream();
            localFile = new File(fileName);
            OutputStream out = new FileOutputStream(localFile);
            int bytesRead;
            int len = NumberConstant.ONE_THOUSAND_AND_TWENTY_FOUR;
            byte[] buffer = new byte[len];
            while ((bytesRead = in.read(buffer, NumberConstant.ZERO, len)) != NumberConstant.MINUS_ONE) {
                out.write(buffer, NumberConstant.ZERO, bytesRead);
            }
            out.close();
            in.close();
            httpUrl.disconnect();
        } catch (Exception e) {
            log.error("网络文件下载失败, e: ", e);
            throw new BusinessException(MyResponseCode.NET_FILE_DOWNLOAD_ERROR);
        }
        return localFile;
    }
}
